import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入路由页面配置
import routes from './routes'
import store from '../store'

// 处理新版本路由警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  routes
})

// 路由守卫=>前置守卫
router.beforeEach((to, from, next) => {
  // 获取token信息
  const { user } = store.state
  // console.log(user)
  const loginConfig = { path: '/login', query: { redirectUrl: to.path } }
  if (to.path.startsWith('/user') && !user?.token) {
    next(loginConfig)
  } else {
    next()
  }
})

export default router
